package camuyen.ltwlibrary.dao;

import org.hibernate.Query;
import org.hibernate.Session;

import camuyen.ltwlibrary.model.User;
import camuyen.ltwlibrary.util.HibernateUtil;

public class UserDao {
    public static User getUser(Long userId) {
        Session session = HibernateUtil.openSession();
        User user = (User) session.load(User.class, userId);
        session.close();
        return user;
    }

    public static void saveUser(User user) {
        Session session = HibernateUtil.openSession();
        session.getTransaction().begin();
        session.save(user);
        session.getTransaction().commit();
        session.close();
    }

    public static void updateUser(User user) {
        Session session = HibernateUtil.openSession();
        session.getTransaction().begin();
        session.update(user);
        session.getTransaction().commit();
        session.close();
    }
    
    public static User getUserByUsername(String username) {
    	Session session = HibernateUtil.openSession();
    	Query query = session.createQuery("SELECT u FROM User u WHERE u.username = :username");
    	query.setParameter("username", username);
    	User user = (User) query.uniqueResult();
        session.close();
    	return user;
    }
    
    public static boolean exists(String username) {
    	User user = UserDao.getUserByUsername(username);
    	if (user != null) {
    		return true;
    	}
    	return false;
    }
}
